package com.innovation.ic.im.end.data.schedule;

import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.im.end.base.value.config.RunEnvConfig;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @desc   定时导入redis数据(定时任务每日导入erp的账号 、 部门数据时, 处理时间内的kafka数据会被丢弃 ， 需要执行当前任务进行redis数据手动导入操作)
 * @author linuo
 * @time   2022年10月26日11:14:32
 */
@Configuration
@EnableScheduling
public class ImportRedisDataTask extends AbstractSchedule {
    private static final Logger log = LoggerFactory.getLogger(ImportRedisDataTask.class);

    @Resource
    private RunEnvConfig runEnvConfig;

    /**
     * 文件头名
     */
    private static String fileHeadName = "import-redis-";

    /**
     * 文件后缀
     */
    private static String fileNameSuffix = ".sh";

    @Scheduled(cron = "0 0 3 * * ?")
    private void importRedisData() {
        try {
            log.info("导入redis数据定时任务,开始");
            InterProcessMutex lock = new InterProcessMutex(curatorFramework, zookeeperPathDataParamConfig.getImportRedisData());
            if (lock.acquire(zookeeperParamConfig.getWaitingLockTime(), TimeUnit.SECONDS)) {
                log.info("导入redis数据定时任务(importRedisData)开启");

                // 执行脚本文件
                implementShell();
                log.info("导入redis数据定时任务(importRedisData)执行完成");
            }else {
                log.info("导入redis数据定时任务,获取锁失败,不执行脚本定时任务");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取redis脚本并执行
     * @return
     */
    public List<String> implementShell() {
        List<String> result = new ArrayList<>();
        String sourceFileName = fileHeadName + runEnvConfig.getEnv() + fileNameSuffix;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(sourceFileName);
        BufferedInputStream in = null;
        BufferedReader br = null;
        try {
            in = new BufferedInputStream(inputStream);
            br = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = br.readLine()) != null) {
                if (StringUtils.isNotEmpty(line)) {
                    log.info("执行脚本命令:" + line);
                    Process exec = Runtime.getRuntime().exec(line);
                    //等待当前线程结束后在执行下一条
                    int i = exec.waitFor();
                    result.add(line);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭流
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}